package com.ruoyi.web.controller.business;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.bo.HcxMerchantAddBo;
import com.ruoyi.business.bo.HcxMerchantEditBo;
import com.ruoyi.business.bo.HcxMerchantQueryBo;
import com.ruoyi.business.domain.HcxAppUser;
import com.ruoyi.business.domain.HcxMerchant;
import com.ruoyi.business.mapper.HcxAppUserMapper;
import com.ruoyi.business.service.IHcxMerchantService;
import com.ruoyi.business.vo.HcxMerchantVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商家Controller
 *
 * @author wsdz
 * @date 2022-08-17
 */
@Api(value = "商家控制器", tags = {"商家管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/business/merchant")
public class HcxMerchantController extends BaseController {

    private final IHcxMerchantService iHcxMerchantService;

    private final HcxAppUserMapper hcxAppUserMapper;

    /**
     * 查询商家列表
     */
    @ApiOperation("查询商家列表")
    @PreAuthorize("@ss.hasPermi('business:merchant:list')")
    @GetMapping("/list")
    public TableDataInfo<HcxMerchantVo> list(@Validated HcxMerchantQueryBo bo) {
        return iHcxMerchantService.queryPageList(bo);
    }

    /**
     * 导出商家列表
     */
    @ApiOperation("导出商家列表")
    @PreAuthorize("@ss.hasPermi('business:merchant:export')")
    @Log(title = "商家", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult<Void> export(@Validated HcxMerchantQueryBo bo) {
        List<HcxMerchantVo> list = iHcxMerchantService.queryList(bo);
        ExcelUtil<HcxMerchantVo> util = new ExcelUtil<>(HcxMerchantVo.class);
        return util.exportExcel(list, "商家");
    }

    /**
     * 获取商家详细信息
     */
    @ApiOperation("获取商家详细信息")
    @PreAuthorize("@ss.hasPermi('business:merchant:query')")
    @GetMapping("/{id}")
    public AjaxResult<HcxMerchantVo> getInfo(@NotNull(message = "主键不能为空")
                                             @PathVariable("id") Long id) {
        return AjaxResult.success(iHcxMerchantService.queryById(id));
    }

    /**
     * 新增商家
     */
    @ApiOperation("新增商家")
    @PreAuthorize("@ss.hasPermi('business:merchant:add')")
    @Log(title = "商家", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated @RequestBody HcxMerchantAddBo bo) {
        return toAjax(iHcxMerchantService.insertByAddBo(bo) ? 1 : 0);
    }

    /**
     * 修改商家
     */
    @ApiOperation("修改商家")
    @PreAuthorize("@ss.hasPermi('business:merchant:edit')")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated @RequestBody HcxMerchantEditBo bo) {
        return toAjax(iHcxMerchantService.updateByEditBo(bo) ? 1 : 0);
    }

    /**
     * 删除商家
     */
    @ApiOperation("删除商家")
    @PreAuthorize("@ss.hasPermi('business:merchant:remove')")
    @Log(title = "商家", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
                                   @PathVariable Long[] ids) {
        return toAjax(iHcxMerchantService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    /**
     * 导入商家数据
     */
    @ApiOperation("导入商家数据")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file")
    @PreAuthorize("@ss.hasPermi('business:merchant:import')")
    @Log(title = "商家", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult<Void> importData(MultipartFile file) {

        ExcelUtil<HcxMerchantVo> util = new ExcelUtil<>(HcxMerchantVo.class);
        List<HcxMerchantVo> hcxMerchantList;
        try {
            hcxMerchantList = util.importExcel(file.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("文件解析异常！message：" + e.getMessage());
        }
        String message = iHcxMerchantService.importHcxMerchant(hcxMerchantList);
        return AjaxResult.success(message);

    }

    /**
     * 下载模板
     *
     * @return AjaxResult 模板文件
     */
    @ApiOperation("下载模板")
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<HcxMerchantVo> util = new ExcelUtil<>(HcxMerchantVo.class);
        return util.importTemplateExcel("商家数据");
    }


    /**
     * 获取所有商家列表
     */
    @GetMapping(value = "getAll")
    public AjaxResult<List<HcxMerchant>> getAll() {
        // 获取当前登录用户
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<String> collect = user.getRoles().stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        List<HcxMerchant> list;
        // 如果是超级管理员或者普通管理员 则查询所有商家
        if (SecurityUtils.isAdmin(user.getUserId()) || collect.contains("pugly")) {
            list = iHcxMerchantService.list();
        } else {
            HcxAppUser hcxAppUser = hcxAppUserMapper.selectOne(new LambdaQueryWrapper<HcxAppUser>().eq(HcxAppUser::getPhonenumber, user.getPhonenumber()));
            list = iHcxMerchantService.list(new LambdaQueryWrapper<HcxMerchant>().eq(HcxMerchant::getUserId, hcxAppUser.getId()));
        }
        return AjaxResult.success(list);
    }

    /**
     * 审核商家
     */
    @ApiOperation("审核商家")
    @PreAuthorize("@ss.hasPermi('business:merchant:audit')")
    @Log(title = "商家", businessType = BusinessType.AUDIT)
    @RepeatSubmit
    @PostMapping("/audit")
    public AjaxResult<Void> audit(@Validated @RequestBody HcxMerchantEditBo bo) {
        return toAjax(iHcxMerchantService.audit(bo));
    }

    /**
     * 获取商家详细信息
     */
    @ApiOperation("获取商家详细信息")
    @PreAuthorize("@ss.hasPermi('business:MerchantDetail:detail')")
    @GetMapping("/detail")
    public AjaxResult<HcxMerchantVo> getInfo() {
        return AjaxResult.success(iHcxMerchantService.queryDetail());
    }

    /**
     * 修改商家营业信息
     */
    @ApiOperation("修改商家")
    @PreAuthorize("@ss.hasPermi('business:merchant:edit')")
    @Log(title = "商家", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PostMapping("/business")
    public AjaxResult<Void> updateMerchantYingye(@Validated @RequestBody HcxMerchantEditBo bo) {
        return toAjax(iHcxMerchantService.updateMerchantYingye(bo) ? 1 : 0);
    }

}
